<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');

class Auth {

	var $CI;

	function  __construct()
	{
		$this->CI =& get_instance();
		log_message('debug', 'Authorization class initialized.');
	}

	function login($username, $password) 
	{
		$this->CI->db->select('id, salt, password');
		
		$query = $this->CI->db->get_where('users', array('username'=>$username), 1, 0);
		
		// username exists so proceed to password verification
		if ($query->num_rows != 1) 
		{
			return FALSE;
		}
		else
		{
			$row = $query->row();
				
			if ($this->check_password($password, $row->salt, $row->password))
			{
				$this->CI->session->set_userdata(array('user_id'=>$row->id));
				return TRUE;
			}
			
			return FALSE;
		}
	}
	
	function check_password($password, $salt, $hashed_pwd)
	{
		$this->CI->load->helper('security');
		
		if (dohash($password.$salt, 'sha1') === $hashed_pwd) 
		{
			return TRUE;
		}
		else
		{
			return FALSE;  
		}
	}

	
	public function logout()
	{
		$this->CI->session->unset_userdata('user_id');
	}

	function get_user($id)
	{
		if ($id)
		{
			$this->CI->db->select('id, username, email, created_on, status, realname');
			$query = $this->CI->db->get_where('users', array('users.id'=>$id), 1, 0);
			
			if ($query->num_rows() == 1)
			{
				return $query->row();
			}
			else
			{
				return FALSE;
			}
		}
		else
		{
			return FALSE;
		}
	}
}
